package com.you.rpc;

import com.you.rpc.base.ObjectDecoder;
import com.you.rpc.base.ObjectEncoder;
import com.you.rpc.server.ServerHandler;
import com.you.rpc.server.UserProcessor;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RpcServer {
    private String hostname;
    private int port;
    private String address;
    private EventLoopGroup parentGroup = new NioEventLoopGroup(1);
    private EventLoopGroup childrenGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors());
    private ServerHandler serverHandler = new ServerHandler();
    private ChannelFuture channelFuture;
    private UserProcessor userProcessor;

    public RpcServer(int port) {
        this("localhost", port);
    }

    public RpcServer(String hostname, int port) {
        this.hostname = hostname;
        this.port = port;
        this.address = hostname + ":" + port;
    }

    public String getAddress() {
        return address;
    }

    public <T> void registerUserProcessor(UserProcessor<T> userProcessor) {
        this.userProcessor = (UserProcessor<T>) userProcessor;
        this.serverHandler.setProcessors(this.userProcessor);
    }

    public void start() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(parentGroup, childrenGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new ObjectEncoder());
                        pipeline.addLast(new ObjectDecoder());
                        pipeline.addLast(serverHandler);
                    }
                });
        channelFuture = serverBootstrap.bind(hostname, port);
        log.info("RPC Server启动");
    }

    public void destroy() throws InterruptedException {
        if (channelFuture != null) {
            channelFuture.channel().closeFuture().sync();
        }
        parentGroup.shutdownGracefully();
        childrenGroup.shutdownGracefully();
        log.info("RPC Server关闭");
    }
}
